package com.web;

import com.bean.Student;
import com.dao.StudentDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;

@WebServlet("/student/update")
public class StuUpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String no = req.getParameter("no");

        try {
            Student students = new StudentDao().get(no);
            req.setAttribute("students", students);
            req.getRequestDispatcher("/student/update.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("message", "单条信息查询失败！" + e.getLocalizedMessage());
            req.getRequestDispatcher("/student/list.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String no = req.getParameter("no");
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String sex = req.getParameter("sex");
        String score = req.getParameter("score");
//        Timestamp time = Timestamp.valueOf(req.getParameter("time"));
        Date time = Date.valueOf(req.getParameter("time"));

        try {
            new StudentDao().update(no, name, Integer.parseInt(age), sex, Float.parseFloat(score), time);
            req.setAttribute("message", "更新成功");
            req.getRequestDispatcher("/student/message.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("message", "更新失败！" + e.getLocalizedMessage());
            req.getRequestDispatcher("/student/message.jsp").forward(req, resp);
        }
    }
}
